package com.entmanage.base.oa.controller;

import com.entmanage.base.oa.domain.OaOvertimeApply;
import com.entmanage.base.oa.service.impl.OaLeaveApplyServiceImpl;
import com.entmanage.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.entmanage.common.annotation.Log;
import com.entmanage.common.core.controller.BaseController;
import com.entmanage.common.core.domain.AjaxResult;
import com.entmanage.common.enums.BusinessType;
import com.entmanage.base.oa.domain.OaReimbursementApply;
import com.entmanage.base.oa.service.IOaReimbursementApplyService;
import com.entmanage.common.utils.poi.ExcelUtil;
import com.entmanage.common.core.page.TableDataInfo;

/**
 * OA报销申请主Controller
 *
 * @author lsq
 * @date 2025-09-25
 */
@Api(tags = {"oa-OaReimbursementApply模块"}, description = "OA报销申请主")
@RestController
@RequestMapping("/oa/reimbursement_apply")
public class OaReimbursementApplyController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(OaLeaveApplyServiceImpl.class);

    @Autowired
    private IOaReimbursementApplyService oaReimbursementApplyService;

    /**
     * 查询OA报销申请主列表
     */
    @PreAuthorize("@ss.hasPermi('oa:reimbursement_apply:list')")
    @GetMapping("/list")
    public TableDataInfo list(OaReimbursementApply oaReimbursementApply)
    {
        // ✅ 判断当前用户是否具备“查看所有数据”的权限
        if (!getLoginUser().getUser().isAdmin()) {
            // 没有权限 → 只能查自己的数据
            Long currentUserId = getLoginUser().getUserId();
            // 根据申请人过滤
            oaReimbursementApply.setUserId(currentUserId);
            // 或者如果是按创建人字段存储，也可以用：
            // oaLeaveApply.setCreateBy(currentUserId);
        }

        startPage();
        List<OaReimbursementApply> list = oaReimbursementApplyService.selectOaReimbursementApplyList(oaReimbursementApply);
        return getDataTable(list);
    }

    @GetMapping("/approval/list")
    public TableDataInfo approvalList() {
        Long currentUserId = getLoginUser().getUserId();
        List<OaReimbursementApply> list = oaReimbursementApplyService.selectByApproverId(currentUserId);
        return getDataTable(list);
    }

    @GetMapping("/copied/list")
    public TableDataInfo copiedList() {
        Long currentUserId = getLoginUser().getUserId();
        List<OaReimbursementApply> list = oaReimbursementApplyService.selectByCcId(currentUserId);
        return getDataTable(list);
    }

    /**
     * 导出OA报销申请主列表
     */
    @PreAuthorize("@ss.hasPermi('oa:reimbursement_apply:export')")
    @Log(title = "OA报销申请主", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OaReimbursementApply oaReimbursementApply)
    {
        List<OaReimbursementApply> list = oaReimbursementApplyService.selectOaReimbursementApplyList(oaReimbursementApply);
        ExcelUtil<OaReimbursementApply> util = new ExcelUtil<OaReimbursementApply>(OaReimbursementApply.class);
        util.exportExcel(response, list, "OA报销申请主数据");
    }

    /**
     * 获取OA报销申请主详细信息
     */
    @PreAuthorize("@ss.hasPermi('oa:reimbursement_apply:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(oaReimbursementApplyService.selectOaReimbursementApplyById(id));
    }

    /**
     * 新增OA报销申请主
     */
    @PreAuthorize("@ss.hasPermi('oa:reimbursement_apply:add')")
    @Log(title = "OA报销申请主", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OaReimbursementApply oaReimbursementApply)
    {
        return toAjax(oaReimbursementApplyService.insertOaReimbursementApply(oaReimbursementApply));
    }

    /**
     * 修改OA报销申请主
     */
    @PreAuthorize("@ss.hasPermi('oa:reimbursement_apply:edit')")
    @Log(title = "OA报销申请主", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OaReimbursementApply oaReimbursementApply)
    {
        return toAjax(oaReimbursementApplyService.updateOaReimbursementApply(oaReimbursementApply));
    }

    /**
     * 删除OA报销申请主
     */
    @PreAuthorize("@ss.hasPermi('oa:reimbursement_apply:remove')")
    @Log(title = "OA报销申请主", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(oaReimbursementApplyService.deleteOaReimbursementApplyByIds(ids));
    }

    /**
     * 发送报销审批通知邮件
     */
    @PreAuthorize("@ss.hasPermi('oa:reimbursement_apply:sendEmail')")
    @Log(title = "发送报销审批邮件", businessType = BusinessType.SEND)
    @ApiOperation("发送报销审批邮件")
    @PostMapping("/sendEmail")
    public AjaxResult sendReimbursementApprovalEmail(@RequestBody Map<String, Object> params) {
        try {
            // 获取参数
            List<Long> approverIds = parseIdList(params.get("approverIds"));
            List<Long> ccIds = parseIdList(params.get("ccIds"));
            String reimbursementType = (String) params.get("reimbursementType");
            String reason = (String) params.get("reason");
            Object totalAmountObj = params.get("totalAmount");
            String totalAmount = totalAmountObj != null ? totalAmountObj.toString() : null;

            // 获取申请人姓名
            String applicantName = getLoginUser().getUser().getNickName();
            if (StringUtils.isEmpty(applicantName)) {
                applicantName = getLoginUser().getUsername();
            }

            // 参数校验
            if (StringUtils.isEmpty(reason)) {
                return AjaxResult.error("报销事由不能为空");
            }
            if (StringUtils.isEmpty(reimbursementType)) {
                return AjaxResult.error("报销类型不能为空");
            }
            if (StringUtils.isEmpty(totalAmount)) {
                return AjaxResult.error("报销总金额不能为空");
            }
            if ((approverIds == null || approverIds.isEmpty()) &&
                    (ccIds == null || ccIds.isEmpty())) {
                return AjaxResult.error("审核人和抄送人均未指定，无法发送邮件");
            }

            // 提交异步任务
            oaReimbursementApplyService.sendReimbursementApprovalEmail(
                    approverIds, ccIds, reimbursementType, reason, totalAmount, applicantName
            );

            return AjaxResult.success("报销审批邮件发送任务已提交，将在后台处理");
        } catch (Exception e) {
            log.error("处理报销邮件发送请求失败", e);
            return AjaxResult.error("系统内部错误：" + e.getMessage());
        }
    }
    /**
     * 安全解析 ID 列表，支持：List<Long>、List<String>、String("1,2,3")、Long、String("5")
     */
    private List<Long> parseIdList(Object obj) {
        if (obj == null) {
            return new ArrayList<>();
        }

        // 情况1：已经是 List<Long>
        if (obj instanceof List) {
            List<?> list = (List<?>) obj;
            return list.stream()
                    .filter(Objects::nonNull)
                    .map(this::convertToLong)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        }

        // 情况2：是字符串，可能是 "1,2,3" 或 "5"
        if (obj instanceof String) {
            String str = (String) obj;
            if (str.isEmpty()) {
                return new ArrayList<>();
            }
            return Arrays.stream(str.split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(s -> {
                        try {
                            return Long.valueOf(s);
                        } catch (NumberFormatException e) {
                            return null;
                        }
                    })
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        }

        // 情况3：单个 Long 或 Integer
        try {
            if (obj instanceof Number) {
                return Arrays.asList(((Number) obj).longValue());
            } else {
                String str = obj.toString().trim();
                if (!str.isEmpty()) {
                    return Arrays.asList(Long.valueOf(str));
                }
            }
        } catch (NumberFormatException e) {
            // 忽略错误
        }

        return new ArrayList<>();
    }

    // 辅助方法：将任意对象转为 Long
    private Long convertToLong(Object o) {
        if (o == null) {
            return null;
        }
        if (o instanceof Long) {
            return (Long) o;
        }
        if (o instanceof Number) {
            return ((Number) o).longValue();
        }
        if (o instanceof String) {
            try {
                return Long.valueOf(((String) o).trim());
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }
}
